package com.smedi.ismedi.authoritymanagement.core.port.adapter.service.impl;

import com.smedi.ismedi.authoritymanagement.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.authoritymanagement.core.port.adapter.service.CallSmsRemoteApiService;
import com.smedi.ismedi.web.starter.exception.LogicException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xulinjun
 * @Date: 2021-8-18 16:47
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CallSmsRemoteApiServiceImpl implements CallSmsRemoteApiService {
    @Value("${tencentCould.secretId}")
    private String secretId;

    @Value("${tencentCould.secretKey}")
    private String secretKey;

    @Value("${tencentCould.appId}")
    private String appId;

    @Value("${tencentCould.templateId}")
    private String templateId;

    private final SmsClient smsClient;

    private final String sign = "上海市政总院";

    @Override
    public void sendSimpleMessage(String mobile, List<String> parameters) {
        List<String> receivers = new ArrayList<>();
        if (mobile.length() > 11) {
            receivers.add(mobile.indexOf("+") < 0 ? "+" + mobile : mobile);
        } else {
            receivers.add("+86" + mobile);
        }

        SendSmsRequest req = new SendSmsRequest();
        req.setPhoneNumberSet(receivers.toArray(new String[receivers.size()])); // 电话号码
        req.setTemplateID(String.valueOf(templateId));
        req.setSign(sign);

        // 参数信息
        if (parameters.size() > 0) {
            req.setTemplateParamSet(parameters.toArray(new String[parameters.size()]));
        }
        req.setSmsSdkAppid(appId); // appId

        try {
            SendSmsResponse resp = smsClient.SendSms(req);
            log.info("短信发送结果: {}", SendSmsResponse.toJsonString(resp));
        } catch (Exception e) {
            log.error("错误：{}", e);
            throw LogicException.raise(CustomError.SEND_SMS_ERROR);
        }
    }
}
